import groovy.json.JsonSlurper

import java.text.SimpleDateFormat

//  https://www.w3cschool.cn/groovy/groovy_file_io.html
// Groovy读取文件信息
// https://www.cnblogs.com/alansheng/p/4788237.html
class TestFile {

    public static void main(String[] args) {

        println("*****************     读取文件     *********************")

        readFile()


        println("*****************     写入文件     *********************")

        writeFile("src\\file\\two.txt")
        writeFile2("src\\file\\two2.txt")

        println("*****************     复制文件     *********************")

        copyFile()

        println("*****************     操作目录     *********************")

        handleDictionary()
    }

    private static void handleDictionary() {
        def dir = new File("src", "\\file")
        if (dir.isDirectory()) {
            dir.eachFileRecurse { file ->
                println file
            }
        }

        //使正则表达式匹配文件名
        dir.eachFileMatch(~/.*\.txt/) { File it -> println it.name }
    }

    private static void copyFile() {
        //可以写入不同的文件类型，拷贝的只是文件内容
        def src = new File("src", "file\\one.txt")
        def dst = new File("src", "file\\three.txt")
        if (!dst.exists()) {
            dst.createNewFile()
        }
        dst << src.text
    }

    private static void readFile() {
        new File("src", 'file\\one.txt').eachLine { line ->
            println line
        }

        new File("src", 'file\\one.txt').eachLine { line, lineNum ->
            println(lineNum + " " + line)
        }

        //读取文件的内容到字符串
        File file = new File("src", "file\\one.txt")
        println file.text
    }

    def static writeFile(fileName) {
        new File(fileName).withWriter('utf-8') { writer ->
            writer.write('The first content of file')
            writer.write('\n')
            writer.write('The first content of file')
            writer.write('\n')
            writer.write("name : xq")
            writer.write('\n')
            writer.write("time : ${getTime()}")
        }
    }

    def static writeFile2(fileName) {
        def file = new File(fileName)

        if (file.exists())
            file.delete()

        def printWriter = file.newPrintWriter() //

        printWriter.write('The first2 content of file')
        printWriter.write('\n')
        printWriter.write('The first2 content of file')
        printWriter.write('\n')
        printWriter.write("name : xq2")
        printWriter.write('\n')
        printWriter.write("time2 : ${getTime()}")

        printWriter.flush()
        printWriter.close()
    }

    def static getTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        return sdf.format(calendar.getTime());
    }
}
